package com.wangsai.framework.supersecurity.core.context;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.wangsai.framework.supersecurity.core.SuperSecurityManager;
import com.wangsai.framework.supersecurity.core.UserRequest;
import com.wangsai.framework.supersecurity.core.context.chain.UserContextFilter;
import com.wangsai.framework.supersecurity.core.context.chain.UserContextFilterChain;
import com.wangsai.framework.supersecurity.core.exception.NotLoginException;

import java.util.List;
import java.util.Optional;

/**
 * 用户上下文
 *
 * @author Mr.Wang
 * @date 2021-08-14 15:41
 */
public class UserContext {


    public static <T> T currentUser(Class<T> clazz) {
        Optional<T> userOptional = currentUserOfNullable(clazz);
        if (!userOptional.isPresent()) {
            throw new NotLoginException();
        }
        return userOptional.get();
    }


    public static Optional<JSONObject> currentUserOfNullable() {
        List<UserContextFilter> userContextFilters = SuperSecurityManager.getUserContextFilters();
        UserContextFilterChain filterChain = new UserContextFilterChain();
        for (UserContextFilter userContextFilter : userContextFilters) {
            filterChain.addFilter(userContextFilter);
        }
        UserRequest userRequest = new UserRequest();
        userRequest.setHasUser(false);
        filterChain.doFilter(userRequest, filterChain);
        if (userRequest.isHasUser() && CollectionUtil.isNotEmpty(userRequest.getUser())) {
            return Optional.of(userRequest.getUser());
        }
        return Optional.empty();
    }


    public static <T> Optional<T> currentUserOfNullable(Class<T> clazz) {
        Optional<JSONObject> jsonUserOptional = UserContext.currentUserOfNullable();
        return jsonUserOptional.map(jsonObject -> BeanUtil.toBeanIgnoreError(jsonObject, clazz));
    }
}